package com.axend.lib_base.view.dialog

import android.app.Dialog
import android.content.Context
import android.view.WindowManager
import androidx.databinding.DataBindingUtil
import com.axend.lib_base.R
import com.axend.lib_base.databinding.BaseDialogCustomCountDownBinding
import com.axend.lib_base.ext.dp2px
import com.axend.lib_base.help.CountdownHelper

/**
 * @description自定义 倒计时弹窗
 * @author admins
 * @time 2024/8/27 17:55
 */
class CustomCountDownDialog(context: Context) :
    Dialog(context, R.style.Common_CustomAlarmDialog) {

    private var dialogBinding: BaseDialogCustomCountDownBinding
    private var countdownHelper: CountdownHelper?=null

    companion object {
        @Volatile
        private var instance: CustomCountDownDialog? = null

        fun getInstance(context: Context): CustomCountDownDialog {
            return instance ?: synchronized(this) {
                instance ?: createInstance(context).also { instance = it }
            }
        }

        private fun createInstance(context: Context): CustomCountDownDialog {
            return CustomCountDownDialog(context).apply {
                // 初始化Dialog的配置，比如设置视图、按钮监听器等
                setCancelable(true)
                // 这里可以根据需要设置对话框的内容，例如使用自定义布局
            }
        }
    }


    init {
        dialogBinding = DataBindingUtil.inflate(
            layoutInflater,
            R.layout.base_dialog_custom_count_down,
            null,
            false
        )
        setContentView(dialogBinding.root)
        setCanceledOnTouchOutside(false)
        val window = window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        //设置提示框位置
        val lp = window!!.attributes
        //lp.gravity = Gravity.TOP | Gravity.LEFT;
        //lp.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
        //lp.x = DisplayUtils.dip2px(53);
        //lp.y = DisplayUtils.dip2px(186);
        lp.width = dp2px(580f)
        window.attributes = lp
//        dialogBinding.tvContent.text = context.getString(R.string.app_tips_radar_disconnected)
        dialogBinding.btOk.setOnClickListener {
            dismiss()
        }



    }


    override fun show() {
        super.show()
        // 初始化倒计时工具类
        countdownHelper =
            CountdownHelper(10000, object : CountdownHelper.OnCountdownFinishedListener {
                override fun onCountdownFinished() {
                    /*倒计时结束 finish*/
                    dismiss()
                }

                override fun onCountdownTick(time: String) {
                    dialogBinding.btOk.text =
                        "${getContext().getString(R.string.app_dialog_ok)}($time)"
                }
            })

        // 启动倒计时
        countdownHelper?.startCountdown()
    }

}